package com.seniorproject.aims;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServletEnrollOld")
@MultipartConfig(fileSizeThreshold=1024*1024*10, 	// 10 MB 
				 maxFileSize=1024*1024*50,      	// 50 MB
				 maxRequestSize=1024*1024*100)   	// 100 MB
public class UploadServletEnrollOld extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	 private static final String UPLOAD_DIRECTORY = "upload";
	    private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
	    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
	    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
	    private static final String UPLOAD_DIR = "upload";

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("@UploadServletEnrollOld");
		
		
		String student_id = getValue(request.getPart("student_id"));
		
		request.setAttribute("student_id",student_id);
		Part filePart = request.getPart("uploadFile"); // Retrieves <input type="file" name="file">
	    String fileNameOld = filePart.getSubmittedFileName();
	    String file_extension ="";
	    String[] file_extension_temp = fileNameOld.split("\\.");
	    file_extension = "."+file_extension_temp[1];
	    System.out.println("file_extension:"+file_extension);
	    
	   
	    OutputStream out = null;
	    InputStream filecontent = null;
	    final PrintWriter writer = response.getWriter();

	    
	    System.out.println("fileName:"+fileNameOld);
	    request.setAttribute("fileNameOld", fileNameOld);

	    	try{
                	
                	Date date = new Date();
                	String temp_year = date.getYear()+1900+"";
					String temp_month = date.getMonth()+1+"";
					String temp_date = date.getDate()+"";
					String temp_hour = date.getHours()+"";
					String temp_minute = date.getMinutes()+"";
					String temp_second = date.getSeconds()+"";
                	
                    String fileName =  temp_year+temp_month+temp_date+temp_hour+temp_minute+temp_second+file_extension;
                    
                    // gets absolute path of the web application
                    String applicationPath = request.getServletContext().getRealPath("");
                    // constructs path of the directory to save uploaded file
                    String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
                      
                    // creates the save directory if it does not exists
                    File fileSaveDir = new File(uploadFilePath);
                    if (!fileSaveDir.exists()) {
                        fileSaveDir.mkdirs();
                    }
                    System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());
                    out = new FileOutputStream(new File(uploadFilePath + File.separator
                            + fileName));
                    filecontent = filePart.getInputStream();

                    int read = 0;
                    final byte[] bytes = new byte[1024];

                    while ((read = filecontent.read(bytes)) != -1) {
                        out.write(bytes, 0, read);
                    }
                    writer.println("New file " + fileName + " created at " + uploadFilePath);
                    System.out.println("After write file");
                    
                     
                    
                   
                    request.setAttribute("message",uploadFilePath+"/"+fileName);
	    	}
	    	catch(Exception ex){
	            request.setAttribute("message", "There was an error: " + ex.getMessage());
	            System.out.println("Error occer at UploadServletEnrollOld:"+ex);
		   	}
            
        
        getServletContext().getRequestDispatcher("/enrollold_import_result.jsp").forward(request, response);
    }
	private static String getValue(Part part) throws IOException {
	    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
	    StringBuilder value = new StringBuilder();
	    char[] buffer = new char[1024];
	    for (int length = 0; (length = reader.read(buffer)) > 0;) {
	        value.append(buffer, 0, length);
	    }
	    return value.toString();
	}
	

}
